package westh.ilib.struts.action.croDomainSearch;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.mule.extras.client.MuleClient;
import org.mule.impl.MuleMessage;
import org.mule.umo.UMOMessage;

import java.text.SimpleDateFormat;
import java.util.*;

import net.sf.json.*;
import net.sf.*;

import westh.ilib.bean.croDomainSearch.Resource;
import westh.ilib.bean.croDomainSearch.Author;
import westh.ilib.bean.croDomainSearch.Annotation;
import westh.ilib.service.ResourceService;

/**
 * 
 * author:@author tangjian
 * date changede:Jul 30, 2010
 * modifier: yanfei
 * date changed: 2010-08-10
 * content: refine
 */

public class GetResourceAction extends Action {
	private final static Log log = LogFactory.getLog(GetResourceAction.class);
	
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) 
	{
		//get input Json string
		DynaActionForm f = (DynaActionForm) form;
		String resourceId = f.getString("resourceId");
		//String resourceId="";
		log.debug("Get Resource Action test");
		String ipAddress = request.getRemoteAddr();
		log.debug("ipAddress="+ipAddress);
		//String userId=request.getRemoteUser();
		String userId="1aa8d7a86c4c46cb8cf4bb33e0fb7c4a";
		//if(userId==null)
			//userId="WTF";
		

		
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String clickTimeString = tempDate.format(new java.util.Date());
		
		ResourceService rscService=new ResourceService();
		
		//save click log begin
		String saveLogRetCode=rscService.saveClickLog(request, userId, resourceId, ipAddress, clickTimeString, log);
		//retcode deal function
		
		//save click log end
		
		
		//get resource information by id begin
		String rscOutString = rscService.getResourceById(resourceId, log);
		//String rscOutString="";
		//get resource information by id end
		//Generate resources by search
		String outString="";
		try{
		 //outString=rscService.getResouceListByJson("{\"query\":\"how to read a paper\",\"rscTypeList\":[\"1\",\"2\"],\"rscFieldList\":[\"2\",\"5\"]}",log);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		log.debug("OutString1="+rscOutString);
		//JSONObject json=JSONObject.fromObject(outString);
//		JSONArray resultArray=JSONArray.fromObject(json.getString("result"));
		//
		//request.setAttribute("outString", outString);
		//log.debug("rscOutString="+rscOutString);
		String retCode="4601"; //返回代码
		String retMsg="";//返回结果信息
		String returnStr="fail";//跳转信息
		
		JSONObject jsonRscOut= JSONObject.fromObject(rscOutString);
		//JSONObject jsonRscOut=null;
		retCode = jsonRscOut.getString("retCode");
		String resultStr = jsonRscOut.getString("result");
		if(!resultStr.equals("{}"))
			retCode="4601";
		else
			retCode="4602";
		if (retCode.equals("4601")) 
		{
			
			Resource  resource = new Resource();
			Author firstAuthor=new Author();
			Author [] otherAuthors=null;
			
			
			
			JSONObject resultObj=JSONObject.fromObject(resultStr);
			log.debug("Step into resouce.");
			//JSONObject resultObj=JSONObject.fromObject(resultArray.get(0));
			log.debug("Resource = "+resultStr);
			
			//first author
			String rscFirstAuthorStr = resultObj.getString("rscFirstAuthor");
			if(!rscFirstAuthorStr.equals("")){
				JSONObject rscFirstAuthorObj =  JSONObject.fromObject(rscFirstAuthorStr);
				firstAuthor.setName(rscFirstAuthorObj.getString("name"));
				firstAuthor.setUid(rscFirstAuthorObj.getString("uid"));
				//firstAuthor.setIeeeRefid(rscFirstAuthorObj.getString("ieeeRefid"));
				//firstAuthor.setInstitution(rscFirstAuthorObj.getString("institution"));
			}
			
			//other authors array
			String rscOtherAuthorsStr = resultObj.getString("rscOtherAuthors");
			if(!rscOtherAuthorsStr.equals("")){
				JSONArray rscOtherAuthorsObj =  JSONArray.fromObject(rscOtherAuthorsStr);
			
				int otherAuthorCount=rscOtherAuthorsObj.size();
				otherAuthors=new Author[otherAuthorCount];
			
				for(int i=0;i<otherAuthorCount;i++)
				{
					Author author=new Author();
					JSONObject rscAuthorObj=JSONObject.fromObject(rscOtherAuthorsObj.get(i));
					author.setName(rscAuthorObj.getString("name"));
					author.setUid(rscAuthorObj.getString("uid"));
					//author.setIeeeRefid(rscAuthorObj.getString("ieeeRefid"));
					//author.setInstitution(rscAuthorObj.getString("institution"));
					otherAuthors[i]=author;
				}
			}
			resourceId=resultObj.getString("rscId");
			resource.setRscId(resourceId);
			resource.setRscFirstAuthor(firstAuthor);
			resource.setRscOtherAuthors(otherAuthors);
			resource.setRscTitle(resultObj.getString("rscTitle"));
			resource.setRscCoverage(resultObj.getString("rscCoverage"));
			resource.setRscCreator(resultObj.getString("rscCreator"));
			resource.setRscPublishDate(resultObj.getString("rscPublishDate"));
			resource.setRscAbstract(resultObj.getString("rscAbstract"));
			resource.setRscFormat(resultObj.getString("rscFormat"));
			resource.setRscLanguage(resultObj.getString("rscLanguage"));
			resource.setRscPublisher(resultObj.getString("rscPublisher"));
			resource.setRscRelation(resultObj.getString("rscRelation"));
			resource.setRscRights(resultObj.getString("rscRights"));
			resource.setRscSource(resultObj.getString("rscSource"));
			resource.setRscSubject(resultObj.getString("rscSubject"));
			resource.setRscType(resultObj.getInt("rscType"));
			resource.setRscField(resultObj.getInt("rscField"));
			resource.setRscUrl(resultObj.getString("rscUrl"));
			
			request.setAttribute("resource", resource);
			request.setAttribute("userId", userId);
			//get resource Annotation begin
			String annoOutString=rscService.getResourceAnnoById(resourceId, log);
			//String annoOutString="";
			log.debug("annoOutString="+annoOutString);
			String annoRetCode=""; //返回代码
			String annoRetMsg="";//返回结果信息
//			String annoReturnStr="fail";//跳转信息
			
			JSONObject jsonAnnoOut= JSONObject.fromObject(annoOutString);
			//JSONObject jsonAnnoOut=null;
			annoRetCode = jsonAnnoOut.getString("retCode");
			annoRetMsg = jsonAnnoOut.getString("retMsg");
			
			if(annoRetCode.equals("5500")) //success
			{
			
				String annoResultStr = jsonAnnoOut.getString("result");
				JSONArray annoArray =  JSONArray.fromObject(annoResultStr);
				
				int annoSize=annoArray.size();
				
				ArrayList<Annotation> annoList=new ArrayList<Annotation>();
				//Annotation [] anno = new Annotation[annoSize];
				
				for(int i=0;i<annoSize;i++)
				{
					JSONObject annoObj=JSONObject.fromObject(annoArray.get(i));
					Annotation anno = new Annotation();
					anno.setRscId(resourceId);
					anno.setRscCmt(annoObj.getString("rscDesc"));
					anno.setRscScore(annoObj.getInt("rscScore"));
					anno.setRscReadStatus(annoObj.getInt("rscReadStatus"));
					anno.setUserId(annoObj.getString("userId"));
					anno.setRscTags(annoObj.getString("rscTag"));
					anno.setRscAvgScore(annoObj.getDouble("rscAvgScore"));
					annoList.add(anno);
				}// end for
				
				request.setAttribute("annoList", annoList);
				
			} //end if
			else{
				
			}
			
			//get resource Annotation end
			
			returnStr = "succ";

		}
		if (retCode.equals("4602")) {
			//retMsg = jsonRscOut.getString("retMsg");
			retMsg="Failure in getting resource content from CDO.";
			request.setAttribute("info", retMsg);
			returnStr = "fail";
		}
		
		//get url from cdoi
		
		//get tags and annotations from annosys
		
		return mapping.findForward(returnStr);
	}

}

